﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Models;
using Service.Interface;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using WebAPI.CustomFilter;


namespace WebAPI.Controllers
{
    /// <summary>
    /// 测试
    /// </summary>
    [ApiController]
    [Route("[controller]/[action]")]
    public class TestController : ControllerBase
    {
        Result result = new Result(true);
        private readonly ILogger<ProcessController> _logger;
        private readonly IServices _services;

        public TestController(ILogger<ProcessController> logger, IServices services)
        {
            _logger = logger;
            _services = services;
        }

        /// <summary>
        /// Ado Update
        /// </summary>
        /// <returns></returns>
        [HttpPut]
        public int Update()
        {
            return _services.Update();
        }

        /// <summary>
        /// Ado Del
        /// </summary>
        /// <returns></returns>
        [HttpDelete]
        public int Del()
        {
            return _services.Del();
        }

        /// <summary>
        /// Ado Insert
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public int Insert()
        {
            return _services.Inert();
        }

        /// <summary>
        /// 多租户测试
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public List<Epsntree> Select0()
        {
            var list = _services.ListTentity<Epsntree>();
            return list;
        }

        /// <summary>
        /// 事务测试
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public List<Ppackinfor> Select1()
        {
            var list = _services.ListTentity<Ppackinfor>();
            return list;
        }

        /// <summary>
        /// 多次请求限制测试
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        //[TypeFilter(typeof(AuthFilter))]
        public IEnumerable<Ppackinfor> Get()
        {
            var list = _services.ListTentity<Ppackinfor>();
            return list;
        }

        /// <summary>
        /// 模型验证测试
        /// </summary>
        /// <param name="test"></param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult Test2(Ppackinfor test)
        {
            return new JsonResult(new { code = 500, message = test });
        }

        /// <summary>
        /// 泛型接口方法测试
        /// </summary>
        /// <typeparam name="TEntity"></typeparam>
        /// <param name="model"></param>
        /// <returns></returns>
        public List<TEntity> SelectList<TEntity>(TEntity model)
        {
            throw new NotImplementedException();
        }

        [HttpPost]
        public List<Datemtl> TimLinqtable(string id)
        {
            //var list = GetClassID(id);
            var listtable = _services.ListTentity<Datemtl>();
            var list = GetClassIDS2(listtable, id).ToList();
            return list;
        }


        [NonAction]
        public List<Datemtl> GetClassID(string id)
        {
            var list = _services.ListTentity<Datemtl>();
            var retget = TraverseNodes(list, id).ToList();
            return retget;
        }

        [NonAction]
        public List<Datemtl> GetClassIDS(int id)
        {
            var list = _services.ListTentity<Datemtl>();
            var query = from c in list
                        where c.Parentpart == id.ToString()
                        select c;
            var getdate = query.ToList().Concat(query.ToList().SelectMany(t => GetClassIDS(int.Parse(t.Materialpart)))).ToList();
            return getdate;
        }

        public static List<Datemtl> GetClassIDS2(List<Datemtl> list, string id)
        {
            // var list = _services.ListTentity<TimLinqtable>();
            var results = new List<object>();//new List<Datemtl>();
            var stack = new Stack<string>();
            stack.Push(id);
            while (stack.Count > 0)
            {
                var currentId = stack.Pop();
                var query = from item in list
                            where item.Parentpart.Equals(currentId) && item.Parentrev.Equals("10")
                            select item;
                results.AddRange(query);

                foreach (var item in query)
                {
                    stack.Push(item.Materialpart);
                }
            }
            var ret1 = (from obj in results
                        select new
                        {
                            Company = obj.GetType().GetProperty("Company").GetValue(obj, null).ToString(),
                            Parentpart = obj.GetType().GetProperty("Parentpart").GetValue(obj, null).ToString(),
                            Parentrev = obj.GetType().GetProperty("Parentrev").GetValue(obj, null).ToString(),
                            Mtl = obj.GetType().GetProperty("Mtl").GetValue(obj, null).ToString(),
                            Materialpart = obj.GetType().GetProperty("Materialpart").GetValue(obj, null).ToString(),
                            QtyParent = obj.GetType().GetProperty("QtyParent").GetValue(obj, null).ToString(),
                            Relopr = obj.GetType().GetProperty("Relopr").GetValue(obj, null).ToString(),
                            Scrap = obj.GetType().GetProperty("Scrap").GetValue(obj, null).ToString(),
                            Pullasassembly = obj.GetType().GetProperty("Pullasassembly").GetValue(obj, null).ToString(),
                            Viewasassembly = obj.GetType().GetProperty("Viewasassembly").GetValue(obj, null).ToString(),
                            Groupid = obj.GetType().GetProperty("Groupid").GetValue(obj, null).ToString(),
                            Mtl1 = obj.GetType().GetProperty("Mtl1").GetValue(obj, null).ToString(),
                            Analysiscode = obj.GetType().GetProperty("Analysiscode").GetValue(obj, null).ToString(),
                            Uomcode = obj.GetType().GetProperty("Uomcode").GetValue(obj, null).ToString(),
                            Pngroup_C = obj.GetType().GetProperty("Pngroup_C").GetValue(obj, null).ToString(),
                            Mainpn_C = obj.GetType().GetProperty("Mainpn_C").GetValue(obj, null).ToString()
                        })
                        .Where(t => t.Materialpart != null)
                        .Distinct()
                        .ToList();


            //var ret1 = results.Select(t =>
            //        new
            //        {
            //            t.Company,
            //            t.Parentpart,
            //            t.Parentrev,
            //            t.Mtl,
            //            t.Materialpart,
            //            t.QtyParent,
            //            t.Relopr,
            //            t.Scrap,
            //            t.Pullasassembly,
            //            t.Viewasassembly,
            //            t.Groupid,
            //            t.Mtl1,
            //            t.Analysiscode,
            //            t.Uomcode,
            //            t.Pngroup_C,
            //            t.Mainpn_C
            //        }).Distinct().ToList();

            //var ret1 = results.Select(t =>
            //        new
            //        {
            //            t.Company,
            //            t.Parentpart,
            //            t.Parentrev,
            //            t.Mtl,
            //            t.Materialpart,
            //            t.QtyParent,
            //            t.Relopr,
            //            t.Scrap,
            //            t.Pullasassembly,
            //            t.Viewasassembly,
            //            t.Groupid,
            //            t.Mtl1,
            //            t.Analysiscode,
            //            t.Uomcode,
            //            t.Pngroup_C,
            //            t.Mainpn_C
            //        }).Distinct().ToList();

            //results.FirstOrDefault();
            ////(from p in results select p).Distinct().ToList(); //results.Distinct().ToList();
            //var ret = results.GroupBy(t => t.Materialpart).ToList();
            //var distinc = results.Distinct().ToList();
            return new List<Datemtl>();
        }

        public static IEnumerable<Datemtl> TraverseNodes(List<Datemtl> nodes, string? parentID)
        {
            var children = nodes.Where(node => node.Parentpart == parentID.ToString());
            foreach (var child in children)
            {
                yield return child;
                foreach (var descendant in TraverseNodes(nodes, child.Materialpart))
                {
                    yield return descendant;
                }
            }
        }

        public static IEnumerable<Datemtl> TraverseNodesStack(List<Datemtl> nodes, int? parentID)
        {
            var stack = new Stack<Datemtl>(nodes.Where(node => node.Parentpart == parentID.ToString()));
            while (stack.Any())
            {
                var node = stack.Pop();
                yield return node;

                foreach (var child in nodes.Where(n => n.Parentpart == node.Materialpart))
                {
                    stack.Push(child);
                }
            }
        }


        /*
         /*string company = callContextClient.CurrentCompany;
var joOperDt= result.JobOper;


bool isNeedCust=false;
if(joOperDt==null|| joOperDt.Count()==0)
{
isNeedCust=true;
}

foreach(var item in joOperDt)
{
    if(item.SubContract)
    {
        isNeedCust=true;
        break;
    }
}

var joMtlDt= result.JobMtl;
if((company=="CL-DG" && isNeedCust==false) || company=="CL-HK")//没有委外工序，执行清除报废率 
{

  foreach(var item in joMtlDt)
  {
    decimal scrap=item.EstScrap;
    decimal reqQty=item.RequiredQty;
    if(scrap!=0)
    { 
    item.RequiredQty=reqQty/(scrap/100+1);//恢复原来的需求数量
    item.EstScrap = 0;
    }
  }
  


        //joMtlDt.Where(j => j.RowMod == "U" && j.JobEngineered).FirstOrDefault();
        //string t1= JsonConvert.SerializeObject(joMtlDt);

        //--622-0016-01
        //this.PublishInfoMessage("CSHI:"+t1, Ice.Common.BusinessObjectMessageType.Information, Ice.Bpm.InfoMessageDisplayMode.Individual, "A", "B");


    }


*/

    //string t1= JsonConvert.SerializeObject(joMtlDt.Where(j => j.AnalysisCdDescription == "NCCSAC"));

    //string t1= JsonConvert.SerializeObject(getCostsFromTemp);
    //--622-0016-01
    //this.PublishInfoMessage("CSHI1:"+t1, Ice.Common.BusinessObjectMessageType.Information, Ice.Bpm.InfoMessageDisplayMode.Individual, "A", "B");

    //string t2= JsonConvert.SerializeObject(outWarningList);
    //--622-0016-01
    //this.PublishInfoMessage("CSHI2:"+t2, Ice.Common.BusinessObjectMessageType.Information, Ice.Bpm.InfoMessageDisplayMode.Individual, "A", "B");

    //string t3= JsonConvert.SerializeObject(result);
    //--622-0016-01
    //this.PublishInfoMessage("CSHI3:"+t3, Ice.Common.BusinessObjectMessageType.Information, Ice.Bpm.InfoMessageDisplayMode.Individual, "A", "B");






    }
}
